package com.tuzhi.testjpa.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

@Configuration
public class SecondaryDataSourceConfig {

    /**
     * 扫描spring.datasource.secondary开头的配置信息
     *
     * @return 数据源配置信息
     */
//    @Bean(name = "secondaryDataSourceProperties")
//    @ConfigurationProperties(prefix = "spring.datasource.secondary")
//    public DataSourceProperties dataSourceProperties() {
//        return new DataSourceProperties();
//    }

    @Bean("secondaryDataSource")
    @ConfigurationProperties("my.datasource")
    public DataSource dataSource() {
        return (DruidDataSource) DataSourceBuilder.create().type(DruidDataSource.class).build();
    }

    /**
     * 该方法仅在需要使用JdbcTemplate对象时选用
     *
     * @param dataSource 注入名为secondaryDataSource的bean
     * @return 数据源JdbcTemplate对象
     */
    @Bean(name = "secondaryJdbcTemplate")
    public JdbcTemplate jdbcTemplate(@Qualifier("secondaryDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}
